package db

import (
	"errors"
	"fmt"
	"go_code/gin-blog/model"
	"strconv"
)

//
////func GetArticleList(pageNO, pageSize int) (articleList []*model.ArticleInfo, err error) {
////	if pageNO < 0 || pageSize <= 0 {
////		return
////	}
////	//``id``category_id``content``title``view_count``comment_count``username``STATUS``summary``create_time``update_time``
////	sqlStr := `select id,summary,title,view_count,create_time,comment_count,username,category_id
////				from article where status = 1 order by create_time desc limit ?,?`
////	if err := DB.Select(&articleList, sqlStr, pageNO, pageSize); err != nil {
////		return nil, err
////	}
////	return articleList, nil
////}
//1.查询所有的文章
func GetArticleList(pageNO, pageSize int) ([]*model.ArticleInfo, error) {
	if pageNO < 0 || pageSize <= 0 {
		return nil, errors.New("date format err")
	}
	articleList := []*model.ArticleInfo{}
	if err := DB.Table("article").Order("create_time desc").Limit(pageSize).Offset(pageNO).Find(&articleList).Error; err != nil {
		return nil, err
	}
	return articleList, nil
}

//func GetArticleDetail(id string) (*model.ArticleDetail, error) {
//	articleId, _ := strconv.Atoi(id)
//	fmt.Printf("Id的类型为%T，值为%v\n", articleId, articleId)
//	sqlStr := `select id,category_id,summary,title,view_count,create_time,comment_count,username,content,
//				from article where category_id = ? and  status = 1`
//	var articleDetail model.ArticleDetail
//	//if DB == nil {
//	//	return nil, errors.New("DB empty")
//	//}
//
//	if err := DB.Get(&articleDetail, sqlStr, 2); err != nil {
//		//log.Fatalln(err)
//		return nil, err
//	}
//	//if articleDetail == nil {
//	//	return nil, errors.New("Not Found Record")
//	//}
//	//log.Println(articleDetail)
//	return &articleDetail, nil
//}

//2.根据文章id查询到detail,包括info、content、category
func GetArticleDetail(id string) (*model.ArticleDetail, error) {
	articleId, _ := strconv.Atoi(id)
	articleDetail := new(model.ArticleDetail)
	if err := DB.Table("article").Where("id=?", articleId).First(articleDetail).Error; err != nil {
		return nil, err
	}
	return articleDetail, nil
}

//3.根据categoryId，来查询属于该分类的所有文章
func GetArticleByCategoryId(id int64) (articleRecord []*model.ArticleRecord, err error) {
	if err := DB.Table("article").Where("category_id=?", id).Find(&articleRecord).Error; err != nil {
		return nil, err
	}
	return articleRecord, nil
}

//4.插入文章
func InsertArticleDetail(detail *model.ArticleDetail) (bool, error) {
	fmt.Printf("detail=%v\n", detail)
	//	if err := DB.Table("article").Create(&detail).Error; err != nil {
	//		return false, err
	//	}
	//	return true, nil
	if err := DB.Debug().Raw(`insert into article(category_id,summary,title,content,username,create_time) 
			values(?,?,?,?,?,?)`, `detail.ArticleInfo.CategoryId,detail.Summary,detail.Title,
			detail.Content,detail.Username,1,detail.Create_time`).Error; err != nil {
		return false, err
	}
	return true, nil
}
